package com.sfzd5.exam.helplibrary;

import com.sfzd5.aiclassroom.modle.Question;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoadQeustionImage extends SwingWorker<Integer, Integer> {

    private List<Question> questionList;
    private LoadQuestionListener loadQuestionListener;

    private static Pattern imgUrlPattern;
    private static HashMap<String, Image> imageHashMap;
    private static File cacheDir;

    public static LoadQeustionImage getInstance(){
        return new LoadQeustionImage();
    }

    private LoadQeustionImage(){
        if(imageHashMap==null) {
            cacheDir = new File("imageCacheDir");
            if (!cacheDir.exists())
                cacheDir.mkdir();

            imgUrlPattern = Pattern.compile("data-cke-saved-src=\"(.*?)\"");
            imageHashMap = new HashMap<>();
        }
    }

    public void downLoadImages(List<Question> questionList, LoadQuestionListener loadQuestionListener){
        this.questionList = questionList;
        this.loadQuestionListener = loadQuestionListener;
        this.execute();
    }

    @Override
    protected void done() {
        super.done();
        if(loadQuestionListener!=null)
            loadQuestionListener.over();
    }

    @Override
    protected Integer doInBackground() throws Exception {
        int c = 0;
        List<String> urls = new ArrayList<>();
        for(Question q : questionList){
            if(q.question_text.indexOf("data-cke-saved-src")>0){
                System.out.println("发现了");
            }
            Matcher matcher = imgUrlPattern.matcher(q.question_text);
            while (matcher.find()){
                urls.add(matcher.group(1));
            }
        }

        System.out.println("共有图片："+urls.size());
        for(String url : urls){
            int i = url.lastIndexOf('.');
            String ext = ".png";
            if(i>0){
                ext = url.substring(i);
            }
            String fileName = md5(url)+ext;
            File imageFile = new File(cacheDir, fileName);
            try {
                if(!imageFile.exists()){
                    System.out.println("开始下载："+url);
                    //TODO 此处下载图片需修改
                    //down.downFile(url, imageFile);
                    System.out.println("下载完成："+url);
                }
                if(imageFile.exists()) {
                    imageHashMap.put(url, ImageIO.read(imageFile));
                    c++;
                }
            } catch (IOException e) {
                System.out.println("下载出错："+url);
                e.printStackTrace();
            }
        }
        return c;
    }

    public String md5(String plainText) {
        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        //将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public Image takePicFile(URL src) {
        String url = src.toString();
        if (imageHashMap.containsKey(url))
            return imageHashMap.get(url);
        else
            return null;
    }
}
